package com.huatai.data.jdbc;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

public class SqlUtils {

    public static <T> String generateSql(T t) throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Class clazz = t.getClass();
        String className = clazz.getSimpleName();
        Field[] fields = clazz.getDeclaredFields();
        if (fields == null || fields.length == 0)
            return null;
        StringBuffer sb = new StringBuffer();
        StringBuffer sb1 = new StringBuffer();
        for (Field field : fields) {
            String name = field.getName();
            sb.append(",").append(name);
            Method m = clazz.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1));
            Object value = m.invoke(t);
            if (value instanceof String) {
                sb1.append(",'").append(value).append("'");
            } else if (value instanceof Date) {
                sb1.append(",to_date('").append("?").append("','yyyymmddhh24miss') ");
            } else {
                sb1.append(",").append("?");
            }
        }
        String columnSql = sb.toString().substring(1);
        String valueSql = sb1.toString().substring(1);
        return "insert into " + className + "(" + columnSql + ")values(" + valueSql + ")";
    }


}
